<?php
/**
 * Created by PhpStorm.
 * User: xuzhong
 * Date: 2025/4/3
 * Time: 11:55
 */
declare(strict_types=1);

namespace app\admin\service;

use app\admin\common\ServiceResponse;
use app\admin\model\Classification as ClassificationModel;
use Ramsey\Uuid\Type\Integer;
use think\facade\Db;
use app\admin\model\Warehouse;
class Classification extends BaseService
{
    use ServiceResponse;

    protected $model;

    public function __construct()
    {
        $this->model = new ClassificationModel();
        parent::__construct();
    }
//"id AS value, concat( cusname,' (',email,') ')  as label"
    public function getSelect(array $where): array
    {
        $list = $this->model->where($where)
            ->field('id AS value, cc_name as label')
            ->select()->toArray();
        return [
            'code' => 0,
            'data' => $list
        ];
    }

    /**
     * @describe 分类列表
     * @author: 徐众
     * @date: 2025-04-02 13:02:26
     * @param [] type
     * @return Renderable
     */
    public function getList($where, $page, $limit): array
    {
        $total = $this->model->where($where)->count();
        $countryNum = Db::name('region_country')->where('ccname_id', null)->count();
        if (!$total) {
            return $this->success(['list' => [], 'total' => 0]);
        }
        $list = $this->model->where($where)
            ->field('id,cc_name,sellable_wids,create_time')
            ->page($page, $limit)
            ->select()->toArray();
        foreach ($list as $k=>$v){
            if($v['sellable_wids']){
                #todo  数据太大会存在性能问题，自己用的管理系统 暂时可不优化
                #链式查询会打乱顺序，强制按字段顺序排序
                $name = Db::name('warehouse')->where('id','in',$v['sellable_wids']) ->orderRaw('FIELD(id, ' .  $v['sellable_wids'].')')->column('name');
                if($name && is_array($name)){
                    $list[$k]['sellable_wids'] = implode(',',$name);
                }
            }
        }
        return $this->success(['list' => $list, 'total' => $total,'countryNum'=>$countryNum]);
    }

    /**
     * @describe 可售分类列表
     * @author: 徐众
     * @date: 2025-04-02 13:02:26
     * @param [] type
     * @return Renderable
     */
    public function sellableList($where,$params): array
    {
        if(!isset($params['id']) && !$params['id']){
            return $this->error(500001);
        }
        $list = $this->model->where($where)
            ->field('id,cc_name,sellable_wids,create_time')
            ->select()->toArray();
        if ($list !== null) {
            #获取仓库一级id
            $id = (new Warehouse())->getTopLevelWarehouseId($params['id']);
            foreach ($list as &$item) {
                $item['is_sellable'] = $this->checkSellable($item['sellable_wids'], $id);
            }
        }
        return $this->success(['list' => $list]);
    }
    /**
     * 检查是否可售
     * @param string|null $sellableWids 可售仓库ID字符串
     * @param int $warehouseId 一级仓库ID
     * @return bool
     */
    protected  function checkSellable( $sellableWids, $warehouseId): bool
    {
        if (empty($sellableWids)) {
            return false;
        }
        $sellableWids = explode(',',$sellableWids);
        // 获取交集元素
        $intersection = array_intersect($sellableWids, $warehouseId);

        // 判断是否存在相同元素
        if (!empty($intersection)) {
           return true;
        } else {
            return false;
        }
    }
    /**
     * 创建分类
     * @param array $data 创建物流公司的数据
     */
    public function create($data)
    {
        $country_ids= '';
        if(!empty($data)){
            #是否创建的时候就已经分配国家
            if(isset($data['country_ids'])){
                $country_ids = $data['country_ids'];
                unset($data['country_ids']);
            }
            try {
                #开启事务 创建分类 及分配国家
                    $update = Db::transaction(function () use ($data,$country_ids) {
                    $res = Db::name('cc_names')->insertGetId($data);
                   if($country_ids){
                       // 存在国家id  将国家预分类绑定
                       Db::name('region_country')->where('id', 'in',$country_ids)->update(['ccname_id' => $res]);
                   }
                    return $res;
                });

                if ($update) {
                    $this->clearCTerminalCache(6); // 清除C端产品缓存
                    $this->logger->logOperation($update,'Classification','创建','创建分类');
                    return $this->success();
                } else {
                    return $this->error(500001);
                }
            } catch (\Throwable $th) {
                return $this->error(500001, '服务器内部错误：' . $th->getMessage());
            }
        }else{
            return $this->error(500001, '服务器内部错误' );
        }

    }
    /**
     * 获取分类详情
     * @param int $id 物流公司ID
     */
    public function getOneById($id)
    {
        $customerContact = $this->model->find($id);
        if ($customerContact) {
            $data = $customerContact->append(['creator_value', 'updater_value']);
        }
        $data = $data->toArray();
        if($data){
            $data['sellable_wids'] = empty($data['sellable_wids'])?[]:explode(',', $data['sellable_wids']);
            foreach ($data['sellable_wids'] as &$datum){
                $datum = (int)$datum;
            }
            $country = Db::name('region_country')->where('ccname_id',$data['id'])->field(['id','name','country_code as value'])
                ->select()->toArray();
            $data['countrys'] = $country;
        }
        return $this->success($data);
    }
    /**
     * 更新分类
     * @param int $id 物流公司ID
     * @param array $data 更新物流公司的数据
     */
    public function update($data)
    {
        $res = $this->model->where('id', $data['id'])->find();
        $country_ids = '';
        #是否创建的时候就已经分配国家
        if(isset($data['country_ids'])){
            $country_ids = $data['country_ids'];
            unset($data['country_ids']);
        }
        if (!$res) {
            return false;
        }

        $result =  Db::transaction(function () use ($res,$data,$country_ids) {
            foreach ($data as $key => $value) {
                if ($res->$key != $value) {
                    $res->$key = $value;
                }
            }
            $res->save();
            if($country_ids){
                // 将此分类下的国家ccname_id字段置空
                Db::name('region_country')->where('ccname_id', $data['id'])->update(['ccname_id' => NULL]);
                Db::name('region_country')->where('id','in',$country_ids)->update(['ccname_id' =>$data['id']]);
            }
            return true;
        });
        if ($result) {
            $this->clearCTerminalCache(6); // 清除C端产品缓存
            $this->logger->logOperation($data['id'],'Classification','更新','更新分类');
            return $this->success();
        } else {
            return $this->error(500001);
        }
    }

    /**
     * @describe 删除分类
     * @author: 徐众
     * @date: 2025-04-02 13:02:26
     * @param [] type
     * @return Renderable
     */
    public function delete($param): array
    {
        #校验参数
        if (!isset($param['id']) || empty($param['id'])) {
            return $this->error(100001, '操作失败');
        }
        #查询数据是否存在
        $result = $this->model->where('id', '=', $param['id'])->where('is_del', '=', 0)->select()->toArray();

        if (!empty($result)) {
            #开启事务 删除分类 及置空分类下的国家
            $update = Db::transaction(function () use ($param) {

                Db::name('cc_names')->where('id', $param['id'])->update(['is_del' => time()]);
                // 将此分类下的国家ccname_id字段置空
                Db::name('region_country')->where('ccname_id', $param['id'])->update(['ccname_id' => NULL]);
                return true;
            });
            if ($update) {
                #尝试记录操作日志 不影响主流程
                try {
                    $this->logger->logOperation($param['id'], 'Classification', '删除', '删除分类');
                } catch (\Exception $e) {
                    #记录日志或其他操作
                }
                return $this->success();
            } else {
                return $this->error(500001, '操作失败');
            }

        } else {
            #未找到记录返回失败
            return $this->error(400000, '未找到相关数据');
        }

    }

    /**
     * @describe 分配国家
     * @author: 徐众
     * @date: 2025-04-02 13:02:26
     * @param [] type
     * @return Renderable
     */
    public function distributCountry($param): array
    {
        #校验参数
        if (!isset($param['id']) || empty($param['id']) || !isset($param['country_ids']) || empty($param['country_ids'])) {
            return $this->error(100001, '操作失败');
        }
        #查询数据是否存在
        $result = $this->model->where([
            'id' => $param['id'],
            'is_del' => 0,
        ])->select()->toArray();

        if (!empty($result)) {
            #更新记录
            $country = explode(',',$param['country_ids']);
            #检查国家id是否已经被分配
            $countryList = Db::name('region_country')->where('id','in', $country)->where('ccname_id','not null')->select()->toArray();
            if(empty($countryList)){
                $update = Db::name('region_country')->where('id','in', $country)->update(['ccname_id' => $param['id']]);
                if ($update) {
                    #尝试记录操作日志 不影响主流程
                    try {
                        $this->logger->logOperation($param['country_ids'], 'Classification', '分配', '分配国家到分类');
                    } catch (\Exception $e) {
                        #记录日志或其他操作
                    }
                    return $this->success();
                } else {
                    return $this->error(500001, '操作失败');
                }
            }else {
                return $this->error(500001, '有已分配的国家');
            }
        } else {
            #未找到记录返回失败
            return $this->error(400000, '未找到相关数据');
        }
    }


    /**
     * @describe 选择可售仓库
     * @author: 徐众
     * @date: 2025-04-02 13:02:26
     * @param [] type
     * @return Renderable
     */
    public function availableWarehouse($param): array
    {
        #校验参数
        if (!isset($param['id']) || empty($param['id']) || !isset($param['ids']) || empty($param['ids'])) {
            return $this->error(100001, '操作失败');
        }
        #查询数据是否存在
        $result = $this->model->where([
            'id' => $param['id'],
            'is_del' => 0,
        ])->select()->toArray();

        if (!empty($result)) {
            #更新记录
            $update = $this->model->where('id', '=', $param['id'])->update([
                'sellable_wids' => $param['ids']
            ]);
            if ($update) {
                #尝试记录操作日志 不影响主流程
                try {
                    $this->logger->logOperation($param['ids'], 'Classification', '添加', '添加可售仓库');
                } catch (\Exception $e) {
                    #记录日志或其他操作
                }
                return $this->success();
            } else {
                return $this->error(500001, '操作失败');
            }

        } else {
            #未找到记录返回失败
            return $this->error(400000, '未找到相关数据');
        }
    }


}